package com.littleHan.brushQuestions.web.start.service.impl;

import com.alibaba.fastjson.JSON;
import com.littleHan.brushQuestions.common.Result;
import com.littleHan.brushQuestions.utils.GetTokenInfoUtil;
import com.littleHan.brushQuestions.web.start.dao.GeneralUserDao;
import com.littleHan.brushQuestions.web.start.dao.UserDao;
import com.littleHan.brushQuestions.web.start.pojo.GeneralUser;
import com.littleHan.brushQuestions.web.start.pojo.User;
import com.littleHan.brushQuestions.web.start.service.LoginService;
import com.littleHan.brushQuestions.token.JwtToken;
import com.littleHan.brushQuestions.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private GeneralUserDao generalUserDao;

    @Override
    public String loginDealWith(GeneralUser generalUser) {
        String username = generalUser.getUsername();
        String password = generalUser.getPassword();
        //shiro
        //创建jwt
        Subject subject = SecurityUtils.getSubject();
        //创建jwt token
        String jwt = JwtUtil.createJWT(username, "back", "user", 1000 * 60 * 60 * 24);
        //登录
        JwtToken jwtToken = new JwtToken(jwt, password);
       /*
       认证用户身份,此操作将转移到 自定义 realm对象类中的认证方法中
       认证失败则会抛出如下异常
        */
        try {
            subject.login(jwtToken);
        } catch (UnknownAccountException e) {
            return JSON.toJSONString(new Result().setCode(401).setMessage("账号不存在"));
        } catch (IncorrectCredentialsException e) {
            return JSON.toJSONString(new Result().setCode(401).setMessage("密码错误"));
        }
        //执行到这说明登录成功了，我们将用户信息打包发给前端
        GeneralUser generalUser1 = generalUserDao.getGeneralUserByUsername(username);
        if (!"1".equals(generalUser1.getViolation())) {
            return JSON.toJSONString(new Result().setCode(404).setMessage("您的账号已被封禁无法登录"));
        }
        User user = userDao.getUserByGeneralUserId(generalUser1.getId());
        //为了安全把密码和盐都清空
        generalUser1.setPassword(null);
        generalUser1.setSalt(null);
        //根据用户id生成token
        String jwtByUserId = JwtUtil.createJWT(user.getId(), "back", "user", 1000 * 60 * 60 * 24);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user.getId());
        //map.put("token",jwt);
        map.put("token", jwtByUserId);
        return JSON.toJSONString(new Result().setCode(200).setMessage("登录成功").setData(map));
    }

    @Override
    public GeneralUser getGeneralUserByUsername(String username) {
        GeneralUser generalUser = generalUserDao.getGeneralUserByUsername(username);
        return generalUser;
    }

    @Override
    public Map checkLogin(HttpServletRequest request) {
        String userId=null;
        Map<String,Object> map=null;
        //用于前端请求时，有携带了token的请求头，如果没登录，没有请求头，
        // token解密时候会抛出IllegalArgumentException异常
        try {
            userId = GetTokenInfoUtil.getUserId(request);
        }catch (Exception e) {

        }
        if (userId == null || "".equals(userId)) {
            map=new HashMap<>();
            map.put("loginFlag",false);
            return map;
        }
         GeneralUser user=generalUserDao.getGeneralUserInfo(userId);
        map=new HashMap<>();
        map.put("loginFlag",true);
        map.put("userInfo",user);
        return map;
    }
}
